package com.zzyang.aop.demo.rpc.producer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zzyang.aop.demo.rpc.MyReferenceInvocation;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.CharsetUtil;
import org.springframework.context.ApplicationContext;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * TODO
 *
 * @author zhuoziyang
 * @date 2021/5/19 22:38
 */
public class ProducerNettyServer {

    private final ApplicationContext applicationContext;

    public ProducerNettyServer(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    public void start() throws Exception {
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(boss, worker) // 指定线程组
                .channel(NioServerSocketChannel.class) // 主线程组使用 ServerSocketChannel
                .option(ChannelOption.SO_BACKLOG, 128) // 设置线程队列的连接数
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ServerChannelHandler());
                    }
                });

        System.out.println("服务器已经启动了");

        //绑定端口
        ChannelFuture channelFuture = serverBootstrap.bind(9527).sync();

        channelFuture.channel().closeFuture().sync();
    }

    public class ServerChannelHandler extends ChannelInboundHandlerAdapter {

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            ByteBuf byteBuf = (ByteBuf) msg;
            String request = byteBuf.toString(CharsetUtil.UTF_8);
            System.out.println("客户端发来消息:" + request);
            MyReferenceInvocation myReferenceInvocation = JSONObject.parseObject(request, MyReferenceInvocation.class);

            Object[] args = myReferenceInvocation.getArgs();
            List<String> argTypes = myReferenceInvocation.getArgTypes();

            List<Class> argClassTypes = new ArrayList<>();
            List<Object> convertArgs = new ArrayList<>();
            for (int i = 0; i < argTypes.size(); i++) {
                String className = argTypes.get(i);
                Class<?> clazz = Class.forName(className);
                argClassTypes.add(clazz);
                convertArgs.add(JSONObject.parseObject(JSON.toJSONString(args[i]),clazz));
            }

            Object bean = ProducerNettyServer.this.applicationContext.getBean(Class.forName(myReferenceInvocation.getInterfaceName()));
            Method targetMethod = bean.getClass().getMethod(myReferenceInvocation.getMethodName(), argClassTypes.toArray(new Class[0]));
            ReflectionUtils.makeAccessible(targetMethod);
            Object result = ReflectionUtils.invokeMethod(targetMethod, bean, convertArgs.toArray(new Object[0]));
            String response = JSON.toJSONString(result);
            ctx.channel().writeAndFlush(Unpooled.copiedBuffer(response, CharsetUtil.UTF_8));
        }

        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            super.exceptionCaught(ctx, cause);
        }
    }

}
